#### "How do past repression and indoctrination affect redistributive preferences?" ####
# authors: "Pelke, Lars"
# date: 2019-10-23
# written under "R version 3.6.0 (2019-03-11)"

#### Preliminaries ####

R.version$version.string

# clear workspace
rm(list=ls())

# set working directory

# loading packages

library(countrycode)
library(tidyverse)
library(viridis)
library(scales)
library(labelled)


#### Import Data ####

#Load prepared Survey Data

wvsdata <- readRDS("data/wvsdata_prepared.rds")
essdata <- readRDS("data/essdata_prepared.rds")
evsdata <- readRDS("data/evsdata_prepared.rds")
isspdata <- readRDS("data/issp_prepared.rds")
latinobarometerdata <- readRDS("data/latinobarometer_prepared.rds")

#### Merge Datasets ####

wvsdata <- wvsdata %>%
  mutate(wave = case_when(wave==1 ~ "WVS Wave 1", 
                          wave==2 ~ "WVS Wave 2", 
                          wave==3 ~ "WVS Wave 3", 
                          wave==4 ~ "WVS Wave 4", 
                          wave==5 ~ "WVS Wave 5", 
                          wave==6 ~ "WVS Wave 6", 
                          wave==7 ~ "WVS Wave 7"))

val_labels(wvsdata) <- NULL

merged_data <- wvsdata %>%
  bind_rows(essdata, evsdata, isspdata, latinobarometerdata)

overview_data <- merged_data %>%
  group_by(data) %>%
   count(wave)

#### merged dataset with cowcodes ####

merged_data$cown <- countrycode(merged_data$iso3n, "iso3n", "cown", warn = TRUE)

merged_data$cown[merged_data$iso3n == 200] <- 278 #  	Czechoslovakia
merged_data$cown[merged_data$iso3n == 275] <- 1020  #  	Palestine, State of
merged_data$cown[merged_data$iso3n == 278] <- 265 #  	German Democratic Republic
merged_data$cown[merged_data$iso3n == 344] <- 715 #  	Hong Kong
merged_data$cown[merged_data$iso3n == 630] <- 1014 #  	Puerto Rico
merged_data$cown[merged_data$iso3n == 688] <- 345 #  	Serbia
merged_data$cown[merged_data$iso3n == 1100] <- 347 #  Kosovo

sum(is.na(merged_data$cown))

#### SAVE DATASET ####

merged_data <- merged_data %>%
  dplyr::select(data, iso3n, year, wave, sex, age, education, education_3, birth_year, income_deciles, 
                income_quintiles, social_class, children, unemployed, income_equality, government_resp, 
                cohort_5, cohortmatch5_15, cohortmatch5_20, cown)

saveRDS(merged_data, file = "data/merged_data.rds")


mean.new <- function(v) {
  if (all(is.na(v))) { return(NA) } else { return(mean(v, na.rm=T)) }
}


overview <- merged_data %>%
  group_by(data, wave, iso3n) %>%
  summarize(mean_government_resp = mean.new(education_3))






